package com.gdth.bank.activity;

import java.util.ArrayList;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.gdth.bank.R;
import com.gdth.bank.utils.LogUtils;
import com.gdth.bank.widget.baiduMap.BBDLocationListener;
import com.gdth.core.annotation.view.ViewInject;
import com.gdth.core.widget.BaseActivity;
import com.gdth.widget.dialog.DialogLoader;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class offlineDownActivity extends BaseActivity  implements MKOfflineMapListener{
	
	@ViewInject(id = R.id.header_label_title)
	TextView txt_header_title;
	@ViewInject(id = R.id.header_btn_left, click = "finishClick")
	TextView txt_header_left;
	@ViewInject(id = R.id.header_btn_right, click = "addClick")
	TextView txt_header_right;
	 @ViewInject(id=R.id.download_map, click="onclickdownloadMap") Button download_map;
	 @ViewInject(id=R.id.offline_tishi) TextView offline_tishi;
	 @ViewInject(id=R.id.localmaplistview) ListView list;
	 private int cityId = 0;
	private String cityName = "长沙";
	MKOfflineMap mOffline;
	private LocalMapAdapter lAdapter = null;
	 
	 @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_offline);
//	        getTbxxbList();
	        //初始化界面
	        txt_header_title.setText(getResources().getString(R.string.param250));
	        txt_header_right.setVisibility(View.GONE);
	        InitLocation();
	        mOffline = new MKOfflineMap();
		 	// 传入MKOfflineMapListener，离线地图状态发生改变时会触发该回调
		 	mOffline.init(this);
		
	        lAdapter = new LocalMapAdapter();
	        list.setAdapter(lAdapter);
	        updateView();
	        boolean isAvailable=isNetworkConnected(this);
	        if(isAvailable) {
	        	
	        }
	    }
	  public boolean isNetworkConnected(Context context) {  
	      if (context != null) {  
	          ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
	                  .getSystemService(Context.CONNECTIVITY_SERVICE);  
	         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();  
	          if (mNetworkInfo != null) {  
	              return mNetworkInfo.isAvailable();  
	          }  
	      }  
	     return false;  
	 }  
	  	public LocationClient mLocationClient = null;
	    private MyLocationListener myListener = new MyLocationListener();
	
		protected void InitLocation(){
		
	    	
			mLocationClient = new LocationClient(getApplicationContext());
	        //声明LocationClient类
	        mLocationClient.registerLocationListener(myListener);
	        //注册监听函数
	        LocationClientOption option = new LocationClientOption();
	        //如果开发者需要获得当前点的位置信息，此处必须为true
	        option.setIsNeedLocationDescribe(true);
	        //可选，设置是否需要地址信息，默认不需要
	        option.setIsNeedAddress(true);
	        //可选，默认false,设置是否使用gps
	        option.setOpenGps(true);
	        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
	        option.setLocationNotify(true);
	        //可选，是否需要地址信息，默认为不需要，即参数为false
	        //如果开发者需要获得当前点的地址信息，此处必须为true

	        mLocationClient.setLocOption(option);
	        mLocationClient.start();
		}
	 private ArrayList<MKOLUpdateElement> localMapList = null;
	 public void onclickdownloadMap(View v){  // 地图下载
		 if(cityId == 0) {
			 return ;
		 }
	 		localMapList = mOffline.getAllUpdateInfo();
	 		//mOffline.remove(cityId);
	 		mOffline.start(cityId);
	 		updateView();
	 }
	 
	//  获取离线地图状态
		@Override
		public void onGetOfflineMapState(int type, int state) {
			// TODO Auto-generated method stub
			
			switch (type) {
	        case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {
	            MKOLUpdateElement update = mOffline.getUpdateInfo(state);
	            // 处理下载进度更新提示
	            if (update != null) {
//	                stateView.setText(String.format("%s : %d%%", update.cityName, update.ratio));
	                updateView();
	            }
	        }
	        break;

	        case MKOfflineMap.TYPE_NEW_OFFLINE:
	            // 有新离线地图安装
	        	LogUtils.d("OfflineDemo", String.format("add offlinemap num:%d", state));
	            break;

	        case MKOfflineMap.TYPE_VER_UPDATE:
	            // 版本更新提示
	            // MKOLUpdateElement e = mOffline.getUpdateInfo(state);
	            break;

	        default:
	            break;
	    }
	}
		 public class MyLocationListener implements BDLocationListener {
		        /**
		         * 定位成功之后回调的方法
		         */
		        @Override
		        public void onReceiveLocation(BDLocation location) {
		        	if(null==location){//为空表示百度sdk定位失败  
		        		return;
		            }else{//定位成功  
		            	if(null == location.getProvince() || null == location.getCity()) {
		            		return;
		            	}
		            	mLocationClient.stop();
		            }  
		        //	LogUtils.i("经纬度===", String.valueOf(location.getLongitude()) + "---" + String.valueOf(location.getLatitude()));
		        //	LogUtils.i("省市区===",location.getProvince()+location.getCity()+location.getDistrict());
		        	//ArrayList<MKOLSearchRecord> records = mOffline.searchCity(location.getCity());
		        	
		        	offline_tishi.setText( getResources().getString(R.string.param251) + location.getCity() );
		        	//if (records != null && records.size() == 1) {
		        	 cityId = Integer.valueOf(location.getCityCode());
		        	//}
		        }
		    }
	

		 
		 /**
		     * 离线地图管理列表适配器
		     */
		 public class LocalMapAdapter extends BaseAdapter {

		        @Override
		        public int getCount() {
		        	if(null == localMapList)
		        		return 0;
		            return localMapList.size();
		        }

		        @Override
		        public Object getItem(int index) {
		            return localMapList.get(index);
		        }

		        @Override
		        public long getItemId(int index) {
		            return index;
		        }

		        @Override
		        public View getView(int index, View view, ViewGroup arg2) {
		            MKOLUpdateElement e = (MKOLUpdateElement) getItem(index);
		            view = View.inflate(offlineDownActivity.this,
		                    R.layout.offline_localmap, null);
		            initViewItem(view, e);
		            return view;
		        }

		        void initViewItem(View view, final MKOLUpdateElement e) {
		            Button display = (Button) view.findViewById(R.id.display);
		            Button remove = (Button) view.findViewById(R.id.remove);
		            TextView title = (TextView) view.findViewById(R.id.title);
		            TextView update = (TextView) view.findViewById(R.id.update);
		            TextView ratio = (TextView) view.findViewById(R.id.ratio);
		            ratio.setText(e.ratio + "%");
		            title.setText(e.cityName);
		            display.setVisibility(View.GONE);
		            if (e.update) {
		                update.setText(getResources().getString(R.string.param252));
		            } else {
		                update.setText(getResources().getString(R.string.param253));
		            }

		            if (e.ratio != 100) {
		                display.setEnabled(false);
		            } else {
		                display.setEnabled(true);
		            }

		            remove.setOnClickListener(new OnClickListener() {
		                @Override
		                public void onClick(View arg0) {
		                    mOffline.remove(e.cityID);
		                    updateView();
		                }
		            });

//		            display.setOnClickListener(new OnClickListener() {
//		                @Override
//		                public void onClick(View v) {
//		                    Intent intent = new Intent();
//		                    intent.putExtra("customStyle", true);
//		                    intent.putExtra("x", e.geoPt.longitude);
//		                    intent.putExtra("y", e.geoPt.latitude);
//		                    intent.putExtra("level", 13.0f);
//		                    intent.setClass(OfflineDemo.this, BaseMapDemo.class);
//		                    startActivity(intent);
//		                }
//		            });
		        }

		    }

		 /**
		     * 更新状态显示
		     */
		    public void updateView() {
		        localMapList = mOffline.getAllUpdateInfo();
		        if (localMapList == null) {
		            localMapList = new ArrayList<MKOLUpdateElement>();
		        }
		        lAdapter.notifyDataSetChanged();
		    }
}
